package org.example.microservice.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.example.microservice.common.utils.SequenceUtil;
import org.example.microservice.sys.mapper.DepartmentMapper;
import org.example.microservice.sys.model.form.DepartmentCreateForm;
import org.example.microservice.sys.model.po.Department;
import org.example.microservice.sys.service.DepartmentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Override
    public String createDepartment(DepartmentCreateForm form) {
        Department parentDepartment = baseMapper.selectById(form.getParentId());
        if (parentDepartment == null) {
            return "上级部门不存在";
        }

        int len = 3;
        String latestDepartmentId = baseMapper.selectLatestDepartmentIdInNextLevel(form.getParentId());
        String seq = null;
        if (StringUtils.isNotBlank(latestDepartmentId)) {
            seq = latestDepartmentId.substring(latestDepartmentId.length() - len);
        }
        String id = parentDepartment.getId() + SequenceUtil.nextval(seq, len);

        Department department = new Department();
        BeanUtils.copyProperties(form, department);
        department.setId(id);
        department.setCreateUser("admin");
        department.setCreateTime(new Date());
        baseMapper.insert(department);
        return null;
    }
}
